package core

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"software/global"
	"time"
)

func InitGorm() *gorm.DB {
	if global.Config.Mysql.Host == "" {
		global.Log.Warn("未配置mysql，取消gorm连接")
		return nil
	}
	dsn := global.Config.Mysql.Dsn()

	var mysqlLogger logger.Interface
	//if global.Config.System.Env == "dev" {
	mysqlLogger = logger.Default.LogMode(logger.Info)
	//} else {
	//	//mysqlLogger = logger.Default.LogMode(logger.Error)
	//}

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: mysqlLogger,
	})

	if err != nil {
		global.Log.Fatalf(fmt.Sprintf("[%s]mysql connect error", dsn))

	}

	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour * 4)

	// **设置 MySQL session 时区为东八区**
	_, err = sqlDB.Exec("SET time_zone = '+08:00'")
	if err != nil {
		global.Log.Fatalf("设置数据库时区失败: %v", err)
	}

	//flag.MakeMigrations()

	return db
}
